//
//  Image.m
//  HYHOME
//
//  Created by Mac on 16/1/20.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "Image.h"
#import "ModelOfWater.h"
#import "WaterFlowLayout.h"
#import "UIImageView+WebCache.h"
#import "CellOfWater.h"
#import "NetworkingHandle.h"
#import "MJRefresh.h"
#import "PushImage.h"

#import "DKNightVersion.h"

@interface Image ()<NSURLSessionDataDelegate,NSURLSessionDelegate,NSURLSessionTaskDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,WaterFlowDelegate>

@property (nonatomic, retain) NSMutableData *data;

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *arrImage;
@property (nonatomic, retain) NSMutableArray *arr;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) NSString *strpage;
@property (nonatomic, assign) NSInteger count;

@end

@implementation Image


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.arr = [NSMutableArray array];

    
    
    self.title = @"经典图库";
//    self.strpage = @"action=list&appid=16&appostype=2&appversion=3.1.2&area=0&channel=appstore&color=0&homeType=0&idfa=EEACF35A-5B73-4678-B6EF-E188A26B0232&model=imagessets&page=2&paging=1&perPage=20&style=0&systemversion=9.1&t8t_device_id=82FF5982-855F-471B-8D56-30D0AA7F7D6F&to8to_token=&uid=0&version=2.5";
    
    
    self.strpage = @"action=list&appid=16&appostype=2&appversion=3.1.2&area=0&channel=appstore&color=0&homeType=0&idfa=EEACF35A-5B73-4678-B6EF-E188A26B0232&model=imagessets&page=2&paging=1&perPage=20&style=0&systemversion=9.1&t8t_device_id=82FF5982-855F-471B-8D56-30D0AA7F7D6F&to8to_token=&uid=0&version=2.5";
    self.page = 2;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem =[[ UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    WaterFlowLayout *flowLayout = [[WaterFlowLayout alloc] init];
    
    flowLayout.delegate = self;
    
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 30) / 2;
    flowLayout.itemSize = CGSizeMake(w, 0);
    flowLayout.insertItemSpacing = 10;
    
  
       self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.collectionView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);

    
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[CellOfWater class] forCellWithReuseIdentifier:@"CELL"];
    
    [_collectionView release];
    
    [flowLayout release];
    // 下拉刷新

    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            
            
     self.strpage = [NSString stringWithFormat:@"action=list&appid=16&appostype=2&appversion=3.1.2&area=0&channel=appstore&color=0&homeType=0&idfa=EEACF35A-5B73-4678-B6EF-E188A26B0232&model=imagessets&page=2&paging=1&perPage=20&style=0&systemversion=9.1&t8t_device_id=82FF5982-855F-471B-8D56-30D0AA7F7D6F&to8to_token=&uid=0&version=2.5"];
            self.page = 2;
//
            [self handleData];
            
            
            
            
        });
        
        
        
    }];
    
    self.collectionView.mj_header.automaticallyChangeAlpha = YES;
    
    //上拉加载
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
        self.strpage = [NSString stringWithFormat:@"action=list&appid=16&appostype=2&appversion=3.1.2&area=0&channel=appstore&color=0&homeType=0&idfa=EEACF35A-5B73-4678-B6EF-E188A26B0232&model=imagessets&page=%ld&paging=1&perPage=20&style=0&systemversion=9.1&t8t_device_id=82FF5982-855F-471B-8D56-30D0AA7F7D6F&to8to_token=&uid=0&version=2.5",++self.page];
            
            
            [self handleData2];
          
            [self.collectionView.mj_footer endRefreshing];
            
            
        });
        
        
    }];
    
    

    [self handleData];
    
    


}



- (void)handleData{
    
    
    NSURL *url = [NSURL URLWithString:@"http://mobileapi.to8to.com/smallapp.php"];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod= @"POST";
    
    request.HTTPBody = [self.strpage dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 进入主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
           
            NSError *errorJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
            
            
            NSArray *arrD = [result objectForKey:@"data"];
            
            for (NSDictionary *dic in arrD ) {
                ModelOfWater *model = [[ModelOfWater alloc]init];
                model.title = [dic objectForKey:@"title"];
                model.webUrl = [dic objectForKey:@"webUrl"];

                
                NSArray *arrD2 = [dic objectForKey:@"info"];
                model.fliename = [arrD2[0] objectForKey:@"filename"];
                
                [self.arr addObject:model];
                [model release];
            }
            
            
            
            //
            [self collectionImageArray];
            
            

            [self.collectionView reloadData];
            
            [self.collectionView.mj_header endRefreshing];

        });
        
        
        
        
    }];
    
    
    [task resume];


}


- (void)collectionImageArray {
    
    
    if (!self.arrImage) {
        self.arrImage = [NSMutableArray array];
    }
    
    
    
    for (NSInteger i = self.count; i < self.arr.count; i++) {
        
        [self.arrImage addObject:[UIImage imageNamed:@"jz"]];
        
    }
    
    self.count = self.arr.count;
    
    
    
    for (ModelOfWater *model in self.arr) {
        
        NSInteger index = [self.arr indexOfObject:model];
        
        
        [NetworkingHandle networkingWithURL:model.fliename withIndex:index completeHandel:^(NSURLResponse *response, NSData *data, NSInteger indexInsert) {
            
            
            UIImage *image = [UIImage imageWithData:data];
            
            [self.arrImage replaceObjectAtIndex:index withObject:image];
            
            [self.collectionView reloadData];
            
        }];
        
        
        
    }
    
    
    
}





- (void)handleData2{
    
    NSURL *url = [NSURL URLWithString:@"http://mobileapi.to8to.com/smallapp.php"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod= @"POST";
    
    request.HTTPBody = [self.strpage dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 进入主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            NSError *errorJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
            
            NSArray *arrD = [result objectForKey:@"data"];

            
            for (NSDictionary *dic in arrD ) {
                ModelOfWater *model = [[ModelOfWater alloc]init];
                model.title = [dic objectForKey:@"title"];
                
                
                NSArray *arrD2 = [dic objectForKey:@"info"];
                model.fliename = [arrD2[0] objectForKey:@"filename"];
                
                [self.arr addObject:model];
                
                
                [model release];
            }
            
            [self collectionImageArray];
            [self.collectionView reloadData];
            
            [self.collectionView.mj_header endRefreshing];
            
        });
        
        
        
        
    }];
    
    
    [task resume];
    
    
}



- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath{
    
    
    
    return [CellOfWater height:self.arrImage[indexPath.item]] + 20 + 40;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section{
    
    return self.arrImage.count ;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    // 图片加载后上数据
    CellOfWater *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    
    cell.imageV.image = [self.arrImage objectAtIndex:indexPath.item];
    
    
    cell.labeloftitle.text = [[self.arr objectAtIndex:indexPath.item] title];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    

    PushImage *push = [[PushImage alloc]init];
    
    ModelOfWater *model = [self.arr objectAtIndex:indexPath.item ];
    [push passModel:model];
    [self.navigationController pushViewController:push animated:YES];
    
    


}










- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
